package com.intretech.umsin.datasource.entity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class DBTablesCollection extends ArrayList{

	public boolean add(DBTable dBTable) {
		return super.add(dBTable);
	}
	
	@Override
	public DBTable[] toArray() {	
		return (DBTable[])super.toArray(new DBTable[size()]);	
	}
	
	
	/**
	 * 根据列表索引得到表名
	 * @param tableIndex 列表索引
	 * @return 表名
	 */
	public String getTableName(int tableIndex){		
		try{
			DBTable table = (DBTable)this.get(tableIndex);
			return table.getTableName();
		}
		catch (Exception e) {
			return "" ;
		}
	}
	
	/**
	 * 根据列表索引得到表的数据
	 * @param tableIndex 列表索引
	 * @return 对应表的数据
	 */
	public List getTableData(int tableIndex ){
		try{
			DBTable table = (DBTable)this.get(tableIndex);
			return table.getData();
		}
		catch (Exception e) {
			return Collections.EMPTY_LIST;
		}
	}
	
	/**
	 * 根据表名得到表的数据
	 * @param tablename 表名
	 * @return 对应表的数据
	 */
	public List getTableData(String tablename){		
		List tableData = null;
		try{
			Iterator<DBTable> it = this.iterator();
			while(it.hasNext()){
				DBTable table = it.next();
				if(tablename.equalsIgnoreCase(table.getTableName())){
					tableData = table.getData();
					break;
				}
			}
		}
		catch (Exception e) {
			return tableData=Collections.EMPTY_LIST;
		}
		
		return tableData;
	}

	/**
	 * 根据表名得到表对象
	 * @param tablename 表名
	 * @return
	 */
	public DBTable getDBTable(String tablename){
		DBTable dbTable = null;
		try{
			Iterator<DBTable> it = this.iterator();
			while(it.hasNext()){
				DBTable table = it.next();
				if(tablename.equalsIgnoreCase(table.getTableName())){
					dbTable = table;
					break;
				}
			}
		}
		catch (Exception e) {
			return null;
		}
		return dbTable;
	}
	
	/**
	 * 把数据集以xml的方式输出
	 * @return
	 */
	public String writeToXML() {
		StringBuilder builder = new StringBuilder();
		builder.append("<dataset>");
		builder.append("\n");
		Iterator<DBTable> it = this.iterator();
		while(it.hasNext()){
			DBTable table = it.next();
			builder.append(table.writeToXML());
		}
		builder.append("</dataset>");
		return builder.toString();
	}
	
	/**
	 * 把数据集以xml的方式输出文件
	 * @param path 输出文件路径
	 */
	public void writeToXML(String path) {
		File file = new File(path);
		try (FileOutputStream fop = new FileOutputStream(file)) {

			// if file doesn't exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// get the content in bytes
			byte[] contentInBytes = this.writeToXML().getBytes();

			fop.write(contentInBytes);
			fop.flush();
			fop.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
